import axios from 'axios';
import {BASE_API, EBIZ_API} from '@/config/baseUrl';
import {getToken, setUesrInfo} from '@/utils/localstorage';
import {Message, MessageBox} from 'element-ui';
import router from '@/router/router';

// 创建axios实例
const service = axios.create({
    baseURL: BASE_API, // api的base_url
    timeout: 10000                  // 请求超时时间
})

const eBizService = axios.create({
    baseURL: EBIZ_API,
    timeout: 10000
})
// request拦截器
service.interceptors.request.use(config => {
    // Do something before request is sent
    const token = getToken();
    //console.log('token-->' + token);
    if (token) {
        config.headers['x-access-token'] = token;
        // config['x-area-id'] = window.localStorage.getItem('x-area-id');
    }

    if (config.headers['x-area-id'] == undefined) {
        config.headers['x-area-id'] = 'a';
    }

    return config;
}, error => {
    // Do something with request error
    console.log(error); // for debug
    Promise.reject(error);
})

// response拦截器
service.interceptors.response.use(
    response => {
        //console.log(response);
        let userInfo = JSON.stringify(response.data);
        setUesrInfo(userInfo);
        return response;
    },
    error => {
        const errorCode = error.response.data.code;
        const errorText = error.response.data.error_msg;
        if (errorCode == 40330000) {
            Message.error(errorText);
            router.replace({
                path: '/login',
                query: ''//{redirect: router.currentRoute.fullPath}
            });
            localStorage.clear();//清空本地所有缓存
            //window.location.reload();
        }
        if (errorCode == 40340000) {
            Message.error(errorText);
            // MessageBox.alert(errorText , '提醒', {
            //   confirmButtonText: '确定',
            //   callback: action => {
            //     // this.$message({
            //     //   type: 'info',
            //     //   message: `action: ${ action }`
            //     // });
            //   }
            // });
        }
        console.log(error);// for debug
        return Promise.reject(error)
    }
)

export default service;
